<template>
  <a-form
      :model="form"
      :rules="rules"
      ref="formRef"
      layout="vertical"
  >
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="First name" name="first_name">
          <a-input v-model:value="form.first_name" class="custom-input" @change="onFieldChange" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Last name" name="last_name">
          <a-input v-model:value="form.last_name" class="custom-input" @change="onFieldChange" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-form-item label="Phone Number" name="phone">
      <PhoneNumberInput
          :initialPhoneNumber="form.phone"
          :initialCountryCode="form.countryCode"
          @update:phoneData="handlePhoneData"
      />
      <!-- <div class="form-warning">
        Note: May be used to assist delivery
      </div> -->
      <div class="form-tip">
        We ask for your phone number just incase we need to reach you for any reason regarding your order with
        lannuan.com. We do not rent, share, or sell your personal information. Ever.
      </div>
    </a-form-item>

    <a-form-item label="Address Line 1" name="address">
      <a-auto-complete
          v-model:value="form.address"
          :options="addressOptions"
          placeholder="Please Enter Your Address"
          @search="querySearchAsync"
          @select="autocompleteSelect"
          @change="onFieldChange"
          class="custom-input"
      />
      <div class="form-tip">
        Example: Street, Apartment, suite, building, floor, etc. (38 Skillman St, Apt B6)
      </div>
      <div class="form-warning">
        Note: We're not able to deliver the goods to the Canary Islands，Ceuta and Melilla at the moment, sorry
        for the inconvenience.
      </div>
    </a-form-item>

    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="Recipient Country/Region" name="county">
          <a-select
              v-model:value="form.county"
              @change="changeCountry"
              placeholder="please select Country/Region"
              class="custom-input"
              :options="countryList"
              :field-names="{ label: 'label', value: 'label' }"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="State/Province/Region" name="province">
          <a-input v-model:value="form.province" class="custom-input" @change="onFieldChange" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="City" name="city">
          <a-input v-model:value="form.city" class="custom-input" @change="onFieldChange" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Zip/Postal Code" name="zip_code">
          <a-input v-model:value="form.zipcode" class="custom-input" @change="onFieldChange" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-form-item v-if="showDefaultSwitch">
      <a-switch v-model:checked="defaultSet" @change="changeDefaultSet">
        <template #checkedChildren>Default</template>
        <template #unCheckedChildren>Set as Default</template>
      </a-switch>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { ref, reactive, onMounted, defineProps, defineEmits, watch } from 'vue';
import PhoneNumberInput from "../PhoneNumberInput.vue";
import { getGoogleMap, getMapInfo } from "@/api";
import { countries } from '@/assets/country/country.ts';

const props = defineProps({
  // 表单初始数据
  initialData: {
    type: Object,
    default: () => ({
      user_id: '',
      last_name: '',
      first_name: '',
      name: '',
      address: '',
      county: 'United States',
      province: '',
      city: '',
      zipcode: '',
      phone: '',
      countryCode: '+1',
      country_code: 'US',
      is_default: 0
    })
  },
  // 是否显示默认地址切换
  showDefaultSwitch: {
    type: Boolean,
    default: true
  },
  // 默认地址初始值
  defaultAddress: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits([
  'update:data',
  'update:isDefault',
  'update:isValid',
  'update:phoneValid'
]);

// 表单数据
const form = ref({...props.initialData});

// 确保初始name字段正确设置
if (form.value.first_name || form.value.last_name) {
  form.value.name = `${form.value.first_name || ''} ${form.value.last_name || ''}`.trim();
}

// 监听传入数据变化
watch(() => props.initialData, (newValue) => {
  if (newValue) {
    form.value = {...newValue};

    // 确保name字段正确设置
    if (form.value.first_name || form.value.last_name) {
      form.value.name = `${form.value.first_name || ''} ${form.value.last_name || ''}`.trim();
    }

    // 确保country_code有值，如果没有则根据county设置
    if (!form.value.country_code && form.value.county) {
      const selectedCountry = countryList.value.find(item => item.label === form.value.county);
      if (selectedCountry) {
        form.value.country_code = selectedCountry.value;
        // 手动触发一次表单数据更新
        setTimeout(() => {
          emitUpdateForm();
        }, 0);
      }
    }
  }
}, {deep: true});

// 表单引用
const formRef = ref(null);

// 默认地址
const defaultSet = ref(props.defaultAddress);

watch(() => props.defaultAddress, (newValue) => {
  defaultSet.value = newValue;
});

// 地址自动完成选项
const addressOptions = ref([]);

// 国家列表
const countryList = ref([]);

// 表单校验规则
const rules = {
  first_name: [
    {required: true, message: 'You can\'t leave this empty.', trigger: 'blur'},
  ],
  last_name: [
    {required: true, message: 'You can\'t leave this empty.', trigger: 'blur'},
  ],
  address: [
    {required: true, message: 'You can\'t leave this empty.', trigger: 'blur'},
  ],
  county: [
    {required: true, message: 'You can\'t leave this empty.', trigger: 'blur'},
  ],
  province: [
    {required: true, message: 'You can\'t leave this empty.', trigger: 'blur'},
  ],
  city: [
    {required: true, message: 'You can\'t leave this empty.', trigger: 'blur'},
  ],
};

// 处理普通输入字段变化
const onFieldChange = (e) => {
  // 检查是否为first_name或last_name的变更，立即更新name
  if (e && e.target) {
    const fieldName = e.target.id || '';
    if (fieldName.includes('first_name') || fieldName.includes('last_name')) {
      // 立即更新name字段
      form.value.name = `${form.value.first_name || ''} ${form.value.last_name || ''}`.trim();
    }
  }

  // 使用防抖处理，延迟发送更新
  setTimeout(() => {
    emitUpdateForm();
  }, 100);
};

// 监听表单数据变化并向父组件发送更新
watch(form, (newValue) => {
  // 重新启用表单数据变化监听，确保所有字段更改都能被捕获
  setTimeout(() => {
    emitUpdateForm();
  }, 100);
}, {deep: true});

// 特别监听first_name和last_name变化，更新name字段
watch([() => form.value.first_name, () => form.value.last_name], ([newFirstName, newLastName]) => {
  // 确保有值时才更新
  if (newFirstName || newLastName) {
    // 组合名字，确保即使一个值为空也能正确处理
    form.value.name = `${newFirstName || ''} ${newLastName || ''}`.trim();
    // 不需要立即调用emitUpdateForm，因为form的监听会处理
  }
});

// 特别监听county字段的变化
watch(() => form.value.county, (newValue, oldValue) => {
  if (newValue && newValue !== oldValue) {
    const selectedCountry = countryList.value.find(item => item.label === newValue);
    if (selectedCountry) {
      form.value.country_code = selectedCountry.value;
    } else {
      form.value.country_code = 'US';
    }
    // 通知父组件数据已更新
    emitUpdateForm();
  }
});

// 添加一个防抖处理的辅助函数和状态
const emitUpdateForm = () => {
  // 确保country_code有值
  if (!form.value.country_code && form.value.county) {
    const selectedCountry = countryList.value.find(item => item.label === form.value.county);
    if (selectedCountry) {
      form.value.country_code = selectedCountry.value;
    } else {
      form.value.country_code = 'US';
    }
  }

  // 确保name字段已设置（合并first_name和last_name）
  form.value.name = `${form.value.first_name || ''} ${form.value.last_name || ''}`.trim();

  // 确保表单数据被深拷贝，避免引用问题
  const formData = JSON.parse(JSON.stringify(form.value));
  emit('update:data', formData);
};

// 表单中各个字段变化的处理函数，集中处理避免循环更新
const updateFormField = (fieldName, value) => {
  if (form.value[fieldName] !== value) {
    form.value[fieldName] = value;
    // 主动触发数据更新
    onFieldChange();
  }
};

// 监听默认地址设置
watch(defaultSet, (newValue) => {
  emit('update:isDefault', newValue);
});

// 更改默认地址设置
const changeDefaultSet = (value) => {
  if (value !== defaultSet.value) {
    defaultSet.value = value;

    if (value) {
      form.value.is_default = 1;
    } else {
      form.value.is_default = 0;
    }

    // 只发送默认状态变更事件，不触发完整的数据更新
    emit('update:isDefault', value);

    // 手动触发一次表单数据更新，使用setTimeout避免同步循环
    setTimeout(() => {
      emitUpdateForm();
    }, 0);
  }
};

// 国家变更处理
const changeCountry = (value) => {
  // 更新国家名称
  form.value.county = value;

  // 查找对应的国家代码
  const selectedCountry = countryList.value.find(item => item.label === value);

  // 确保country_code被正确设置
  if (selectedCountry) {
    form.value.country_code = selectedCountry.value;
  } else {
    form.value.country_code = 'US';
  }

  // 直接更新表单数据
  emitUpdateForm();
};

// 处理手机号数据
const handlePhoneData = (phoneData) => {
  if (phoneData && phoneData.isValid) {
    // 不再直接修改form，而是记录有效状态
    emit('update:phoneValid', true);

    // 如果电话号码有变化才更新
    const newPhone = phoneData.data.phoneNumber;
    const newCountryCode = phoneData.data.countryCode;

    let hasChanges = false;
    if (form.value.phone !== newPhone) {
      form.value.phone = newPhone;
      hasChanges = true;
    }

    if (form.value.countryCode !== newCountryCode) {
      form.value.countryCode = newCountryCode;
      hasChanges = true;
    }

    // 只在有变化时发送更新事件
    if (hasChanges) {
      emitUpdateForm();
    }
  } else {
    emit('update:phoneValid', false);
  }
};

// 异步获取地址建议
const querySearchAsync = async (queryString) => {
  if (!queryString || queryString.length < 1) return [];

  try {
    const {data} = await getGoogleMap({
      page: 1,
      page_size: 10,
      address: queryString
    });

    const predictions = JSON.parse(data).predictions || [];
    addressOptions.value = predictions.map(pred => ({
      value: pred.description,
      description: pred.description,
      place_id: pred.place_id,
      structured_formatting: pred.structured_formatting
    }));
    return addressOptions.value;
  } catch (error) {
    console.error('Address request failed:', error);
    return [];
  }
};

// 自动完成选择处理
const autocompleteSelect = (value, option) => {
  form.value.address = option.structured_formatting.main_text;
  getAddressDetails();
  // 确保地址更新会被发送
  emitUpdateForm();
};

// 辅助方法：获取地址详情
const getAddressDetails = async () => {
  const addressParams = {
    page: 1,
    page_size: 10,
    address: form.value.address,
  };
  try {
    const res = await getMapInfo(addressParams);
    if (res.code !== 200) {
      throw new Error(`Failed to fetch address suggestions with code: ${res.code}`);
    }
    if (!Array.isArray(res.data) || res.data.length === 0) {
      // 即使没有获取到详细信息，也需要更新当前的地址
      emitUpdateForm();
      return;
    }
    // 创建临时对象，收集所有变更
    const updates = {};

    res.data.forEach(item => {
      if (Array.isArray(item.types) && item.types.length > 0) {
        if (item.types.includes('postal_code')) {
          updates.zipcode = item.long_name;
        } else if (item.types.includes('administrative_area_level_1')) {
          updates.province = item.long_name;
        } else if (item.types.includes('sublocality_level_1')) {
          updates.city = item.long_name;
        } else if (item.types.includes('locality')) {
          updates.city = item.long_name;
        }
      }
    });

    // 一次性应用所有变更
    if (Object.keys(updates).length > 0) {
      form.value = {...form.value, ...updates};
    }

    // 无论是否有更新，都发送更新事件
    emitUpdateForm();
  } catch (error) {
    console.error('Error fetching address suggestions:', error);
    // 即使出错，也要确保当前输入的地址被更新
    emitUpdateForm();
  }
};

// 表单验证方法
const validate = async () => {
  try {
    // 先确保所有数据都已同步到父组件
    emitUpdateForm();

    // 然后进行表单验证
    await formRef.value.validate();
    emit('update:isValid', true);
    return true;
  } catch (error) {
    emit('update:isValid', false);
    return false;
  }
};

// 重置表单
const resetFields = () => {
  if (formRef.value) {
    formRef.value.resetFields();

    // 恢复到初始数据
    form.value = {...props.initialData};

    // 确保name字段正确设置
    if (form.value.first_name || form.value.last_name) {
      form.value.name = `${form.value.first_name || ''} ${form.value.last_name || ''}`.trim();
    } else {
      form.value.name = '';
    }

    // 特别处理电话相关的字段
    form.value.phone = '';
    form.value.countryCode = '+1';

    // 通知父组件电话验证状态变更为 false
    emit('update:phoneValid', false);

    // 确保更新传递到父组件
    emitUpdateForm();
  }
};

// 提供给父组件的方法
defineExpose({
  validate,
  resetFields,
  formRef
});

// 初始化国家列表
onMounted(() => {
  // 过滤掉重复的alpha2键值，只保留status为assigned的国家
  const uniqueCountries = {};
  countries.forEach((country) => {
    if (country.status === 'assigned' && !uniqueCountries[country.alpha2]) {
      uniqueCountries[country.alpha2] = country;
    }
  });

  countryList.value = Object.values(uniqueCountries).map((country) => {
    return {
      value: country.alpha2,
      label: country.name,
      code: country.countryCallingCodes.map((code) =>
          code.startsWith("+") ? code.slice(1) : code
      )
    };
  });

  // 确保初始化时country_code有值
  if (!form.value.country_code && form.value.county) {
    const selectedCountry = countryList.value.find(item => item.label === form.value.county);
    if (selectedCountry) {
      form.value.country_code = selectedCountry.value;
    } else if (form.value.county) {
      // 如果找不到对应的国家代码，默认设置为US
      form.value.country_code = 'US';
    }
  }

  // 确保初始数据已同步到父组件
  emitUpdateForm();
});
</script>

<style scoped>
.custom-input {
  height: 40px;
  border-radius: 4px;
}

.form-tip {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.form-warning {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
}
</style>

<!--
使用方法:
1. 引入组件:
   import AddressForm from '@/components/common/AddressForm.vue';

2. 在模板中使用:
   <AddressForm
     ref="addressFormRef"
     :initialData="formData"
     :defaultAddress="isDefaultAddress"
     :showDefaultSwitch="true"
     @update:data="onFormDataUpdate"
     @update:isDefault="onDefaultUpdate"
     @update:phoneValid="onPhoneValidUpdate"
   />

3. 组件属性:
   - initialData: 表单初始数据对象
   - defaultAddress: 是否为默认地址
   - showDefaultSwitch: 是否显示默认地址切换开关

4. 组件事件:
   - update:data: 表单数据更新时触发
   - update:isDefault: 默认地址状态更新时触发
   - update:isValid: 表单验证状态更新时触发
   - update:phoneValid: 电话号码验证状态更新时触发

5. 组件方法:
   - validate(): 验证表单，返回Promise
   - resetFields(): 重置表单
   - formRef: 表单引用，可用于直接操作表单

6. 示例数据格式:
   {
     user_id: '',
     last_name: '',
     first_name: '',
     name: '',
     address: '',
     county: 'United States',
     province: '',
     city: '',
     zipcode: '',
     phone: '',
     countryCode: '+1',
     is_default: 0
   }
-->
